<template>
    <div class="container_box">
        <el-scrollbar class="main_box">
            <div class="timeoutReplay">
                <el-form
                    ref="timeoutReplayFormRef"
                    :model="timeoutReplayForm"
                    :rules="timeoutReplayRules"
                    label-width="96px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="规则名称" prop="title">
                                <el-input
                                    v-model="timeoutReplayForm.title"
                                    maxlength="15"
                                    show-word-limit
                                    placeholder="请输入规则名称"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="适用员工" prop="exec_work_user_ids">
                                <ZWSelectDepart
                                    v-model="timeoutReplayForm.exec_work_user_ids"
                                    :tips="tips.tips_worker"
                                    limit="2"
                                    :creators="timeoutReplayForm.exec_work_user_ids_creators"
                                    multiple />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="超时规则" prop="over_time">
                                <TimeoutRule
                                    v-model="timeoutReplayForm.over_time"
                                    v-model:time_unit="timeoutReplayForm.time_unit" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col>
                            <el-form-item label="安静模式" style="display: flex; align-items: center">
                                <el-switch v-model="timeoutReplayForm.is_quiet" :active-value="2" :inactive-value="1" />
                                <span class="form-tips">{{ tips.tips_quiet }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="timeoutReplayForm.is_quiet == 2">
                        <el-col>
                            <el-form-item label="">
                                <QuietTimeQuantum
                                    ref="quietTimeQuantumRef"
                                    v-model="timeoutReplayForm.quiet_mode_time" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col>
                            <el-form-item label="不提醒日期" style="display: flex; align-items: center">
                                <el-switch
                                    v-model="timeoutReplayForm.is_no_remind"
                                    :active-value="2"
                                    :inactive-value="1" />
                                <span class="form-tips">{{ tips.tips_not_remind }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="timeoutReplayForm.is_no_remind == 2">
                        <el-col>
                            <el-form-item label="">
                                <NoRemindDate ref="noRemindDateRef" v-model="timeoutReplayForm.no_remind_date" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col>
                            <el-form-item label="正常结束语" style="display: flex; align-items: center">
                                <el-switch
                                    v-model="timeoutReplayForm.is_open_end_words"
                                    :active-value="2"
                                    :inactive-value="1" />
                                <el-tooltip :content="tips.tips_end_words" placement="top">
                                    <el-icon
                                        style="font-size: 20px; color: #ccc; padding-left: 6px; vertical-align: middle"
                                        ><QuestionFilled
                                    /></el-icon>
                                </el-tooltip>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="timeoutReplayForm.is_open_end_words == 2">
                        <el-col>
                            <el-form-item label="" prop="end_words">
                                <EndWords v-model="timeoutReplayForm.end_words" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col>
                            <el-form-item label="汇总通知" style="display: flex; align-items: center">
                                <el-switch
                                    v-model="timeoutReplayForm.is_open_summary"
                                    :active-value="2"
                                    :inactive-value="1" />
                                <span class="form-tips">{{ tips.tips_summary }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="timeoutReplayForm.is_open_summary == 2">
                        <el-col>
                            <el-form-item label="">
                                <SummaryTime ref="summaryTimeRef" v-model="timeoutReplayForm.summary_time" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="timeoutReplayForm.is_open_summary == 2">
                        <el-col>
                            <el-form-item label="" prop="summary_work_user">
                                <ZWSelectDepart
                                    v-model="timeoutReplayForm.summary_work_user"
                                    label="选择通知员工"
                                    :creators="timeoutReplayForm.summary_work_user_creators"
                                    multiple />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-scrollbar>
        <div class="footer_box">
            <el-button @click="cancal">取消</el-button>
            <el-button type="primary" @click="submit">保存</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch, defineAsyncComponent } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import router from '@/router';
import lodash from 'lodash';
import { tableH, reSize } from '@/utils/utils';
import ZWSelectDepart from '@/components/ZWSelectDepart.vue';
import TimeoutRule from '../components/TimeoutRule.vue';
import EndWords from '../components/EndWords.vue';
import { createRule, getRuleDetailApi, editRule } from '@/api/employe/staffsupervision/timeoutreplay';

const route = useRoute();
const contentHeight = ref<string>('536px');
interface TipsType {
    [k: string]: string;
}
const tips = reactive<TipsType>({
    tips_worker: '仅显示开启了会话存档和授权敏感信的员工',
    tips_quiet:
        '如周一20:00至第二天09:00开启安静模式，在此区间产生的超时未回复不记录超时，将从第二天9点开始之后收到客户消息是开始记录超时未回复时长。',
    tips_not_remind: '以下日期不进行超时提醒',
    tips_end_words: '当客户的最后一条消息包含以下结束语中任意一个时，则停止计算超时时长。',
    tips_summary: '系统每天根据以下时间段对适用员工的超时记录进行汇总通知（数据截止推送时）'
});

const quietTimeQuantumRef = ref<HTMLElement | null>(null);
const noRemindDateRef = ref<HTMLElement | null>(null);
const summaryTimeRef = ref<HTMLElement | null>(null);

const QuietTimeQuantum = ref<any>(null);
const NoRemindDate = ref<any>(null);
const SummaryTime = ref<any>(null);

const timeoutReplayFormRef = ref<FormInstance>();
const timeoutReplayForm = reactive({
    title: '',
    exec_work_user_ids: [],
    exec_work_user_ids_creators: [],
    over_time: 1,
    time_unit: 1,
    is_quiet: 2,
    quiet_mode_time: [],
    is_no_remind: 2,
    no_remind_date: [],
    is_open_end_words: 2,
    end_words: [],
    is_open_summary: 2,
    summary_time: [],
    summary_work_user: [],
    summary_work_user_creators: []
});
const timeoutReplayRules = reactive<FormRules>({
    title: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
    exec_work_user_ids: [{ required: true, message: '请选择适用员工', trigger: 'blur' }],
    over_time: [{ required: true, message: '请填写超时规则', trigger: 'blur' }],
    quiet_mode_time: [{ required: true, message: '请选择安静模式时间', trigger: 'blur' }],
    no_remind_date: [{ required: true, message: '请选择不提醒日期', trigger: 'blur' }],
    end_words: [{ required: true, message: '请输入结束语', trigger: 'blur' }],
    summary_time: [{ required: true, message: '请选择汇总通知时间', trigger: 'blur' }],
    summary_work_user: [{ required: true, message: '请选择通知员工', trigger: 'blur' }]
});

const submit = async () => {
    const promiseArr = await getPromiseArr();
    Promise.all(promiseArr).then(async () => {
        // let params = lodash.cloneDeep(timeoutReplayForm)
        const params = getParams();

        if (route.query.id) {
            if (await editRule(params)) {
                ElMessage.success('规则编辑成功！');
                const path = '/employee/staffsupervision/timeoutreplay';
                router.push({ path });
            }
        } else {
            if (await createRule(params)) {
                ElMessage.success('规则创建成功！');
                const path = '/employee/staffsupervision/timeoutreplay';
                router.push({ path });
            }
        }
    });
};

const getParams = () => {
    const params = lodash.cloneDeep(timeoutReplayForm);
    const { is_quiet, is_no_remind, is_open_end_words, is_open_summary } = timeoutReplayForm;
    if (is_quiet == 1) {
        params.quiet_mode_time = [];
    }
    if (is_no_remind == 1) {
        params.no_remind_date = [];
    }
    if (is_open_end_words == 1) {
        params.end_words = [];
    }
    if (is_open_summary == 1) {
        params.summary_time = [];
        params.summary_work_user = [];
        params.summary_work_user_creators = [];
    }

    if (route.query.id) {
        params['timeout_remind_rule_id'] = route.query.id;
    }
    return params;
};

const getPromiseArr = async () => {
    const { is_quiet, is_no_remind, is_open_end_words } = timeoutReplayForm;
    const arr: any = [];
    arr.push(timeoutReplayFormRef.value?.validate());
    if (is_quiet == 2) {
        arr.push(quietTimeQuantumRef.value?.validate());
    }
    if (is_no_remind == 2) {
        arr.push(noRemindDateRef.value?.validate());
    }
    if (is_open_end_words == 2) {
        arr.push(summaryTimeRef.value?.validate());
    }
    return arr;
};

const cancal = () => {
    router.go(-1);
};

const getHeight = () => {
    const height = tableH('.timeoutReplay', true) as number;
    contentHeight.value = `${height - 74}px`;
};

const getRuleDetail = async (timeout_remind_rule_id: string) => {
    const res = await getRuleDetailApi({ timeout_remind_rule_id });
    const {
        id,
        end_words,
        executor_list: exec_work_user_ids_creators,
        is_no_remind,
        is_open_end_words,
        is_open_summary,
        is_quiet,
        no_remind_date,
        over_time,
        quiet_mode_time,
        summary_time,
        summary_work_user: summary_work_user_creators,
        time_unit,
        title
    } = res;
    const exec_work_user_ids = exec_work_user_ids_creators.map((item: any) => item.id);
    const summary_work_user = summary_work_user_creators.map((item: any) => item.id);

    timeoutReplayForm.end_words = end_words;
    timeoutReplayForm.exec_work_user_ids = exec_work_user_ids;
    timeoutReplayForm.exec_work_user_ids_creators = exec_work_user_ids_creators;
    timeoutReplayForm.is_no_remind = is_no_remind;
    timeoutReplayForm.is_open_end_words = is_open_end_words;
    timeoutReplayForm.is_open_summary = is_open_summary;
    timeoutReplayForm.is_quiet = is_quiet;
    timeoutReplayForm.no_remind_date = no_remind_date;
    timeoutReplayForm.over_time = over_time;
    timeoutReplayForm.quiet_mode_time = quiet_mode_time;
    timeoutReplayForm.summary_time = summary_time;
    timeoutReplayForm.summary_work_user = summary_work_user;
    timeoutReplayForm.summary_work_user_creators = summary_work_user_creators;
    timeoutReplayForm.time_unit = time_unit;
    timeoutReplayForm.title = title;
};

reSize(() => {
    getHeight();
});

const getComponent = (ComName: string) => {
    return defineAsyncComponent(() => {
        return new Promise((resolve, reject) => {
            (async function () {
                try {
                    const res: Promise<any> = await import(`../components/${ComName}.vue`);
                    resolve(res);
                } catch (error) {
                    reject(error);
                }
            })();
        });
    });
};

const init = async () => {
    if (route.query.id) {
        await getRuleDetail(route.query.id as string);
    }
    QuietTimeQuantum.value = await getComponent('QuietTimeQuantum');
    NoRemindDate.value = await getComponent('NoRemindDate');
    SummaryTime.value = await getComponent('SummaryTime');
};

onMounted(async () => {
    getHeight();
    await init();
});
</script>

<style scoped lang="scss">
.timeoutReplay {
    padding: 24px;

    .el-form {
        .el-form-item {
            .form-tips {
                font-size: 12px;
                color: #666;
                margin-left: 8px;
            }
        }
    }
}
</style>
